#!/bin/sh
# Write for quick distribution of a couple of Atlas 200DKs, as same SD cards needed for tens of students, especially after updating the offical image.
#
# Usage:
#
# 1) get backup filesystems (p{1,2,3}.tgz) from a working sdcard, such as /dev/sdb: 
#   su -
#   mount /dev/sdb1 /mnt/ && dump -0uj -f p1.tgz /mnt && umount /mnt
#   mount /dev/sdb2 /mnt/ && dump -0uj -f p2.tgz /mnt && umount /mnt
#   mount /dev/sdb3 /mnt/ && dump -0uj -f p3.tgz /mnt && umount /mnt
#
# 2) clone to a new sdcard, in the path with p{1,2,3}.tgz
#   sudo ./mk_sdcard.sh /dev/sdb
#
# Email: haojiash@qq.com
# Ref: https://stackpointer.io/unix/linux-script-to-partition-disk/632/

DEV=$1
PFSDIR="./"
#DEBUG="echo"
DEBUG=""

help() 
{
  bn=`basename $0`
  cat << EOF
  usage $bn device_node
EOF
}

fdisk_sdcard()
{
  ${DEBUG} fdisk ${DEV} >/dev/null << FDISK_CMDS
o
n

 

+8GiB
n



+1GiB
n

 
 

w
FDISK_CMDS

  partprobe
  sleep 5
}

make_fs()
{ 
  for i in 1 2 3
  do
    ${DEBUG} mkfs.ext3 -F -L ubuntu_fs ${DEV}$i >/dev/null
  done
}

restore_fs()
{
  TMP_MNT="/tmp/mnt.sdcard.fs"

  ${DEBUG} mkdir ${TMP_MNT}
  for i in 1 2 3
  do
    ${DEBUG} mount ${DEV}$i ${TMP_MNT}
    ${DEBUG} cd ${TMP_MNT}
    ${DEBUG} rm -rf *
    ${DEBUG} restore -rf ${PFSDIR}p$i.tgz
    ${DEBUG} cd ..
    ${DEBUG} umount ${TMP_MNT}
  done

  ${DEBUG} rm -rf ${TMP_MNT}
}

main()
{
  #check arguments
  if [ $# -ne 1 ]
  then
    help
    exit 1
  fi

  echo "partition sdcard ..."
  fdisk_sdcard

  echo "make ext3fs ..."
  make_fs
  
  echo "restore files ..."
  restore_fs

}

main $*
ret=$?

if [ $ret -ne 0 ];then
    echo "Failed" 
    exit 1
fi
echo "Success"
exit 0
